import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../providers/font_size_provider.dart';
import '../repositories/check_in_record_repository.dart';

class MyProfileScreen extends StatefulWidget {
  const MyProfileScreen({super.key});

  @override
  State<MyProfileScreen> createState() => _MyProfileScreenState();
}

class _MyProfileScreenState extends State<MyProfileScreen> {
  final CheckInRecordRepository _recordRepository = CheckInRecordRepository();
  int _consecutiveDays = 0;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadCheckInStats();
  }

  Future<void> _loadCheckInStats() async {
    try {
      final stats = await _recordRepository.getCheckInStats();
      setState(() {
        _consecutiveDays = stats['consecutiveDays'] ?? 0;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _consecutiveDays = 0;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final fontSizeProvider = Provider.of<FontSizeProvider>(context);
    final textScaleFactor = fontSizeProvider.fontScale;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '我的',
          style: TextStyle(
            fontFamily: 'FangSong',
            fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 用户信息卡片
          _buildUserInfoCard(context, textScaleFactor),
          
          const SizedBox(height: 16),
          
          // 功能列表
          _buildFunctionItem(
            context: context,
            icon: Icons.calendar_today,
            title: '每日签到',
            subtitle: '坚持学习，收获成长',
            onTap: () => context.push('/profile/check-in'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.chat,
            title: 'AI助手',
            subtitle: '智能学习助手',
            onTap: () => context.push('/profile/ai-chat'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.note,
            title: '我的笔记',
            subtitle: '查看所有笔记',
            onTap: () => context.push('/profile/notes'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.article,
            title: '我的作文素材',
            subtitle: '查看所有素材',
            onTap: () => context.push('/profile/essay-materials'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.backup,
            title: '我的备份',
            subtitle: '数据备份与恢复',
            onTap: () => context.push('/profile/backup'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.palette,
            title: '我的主题',
            subtitle: '个性化主题设置',
            onTap: () => context.push('/profile/theme-settings'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          
          _buildFunctionItem(
            context: context,
            icon: Icons.text_fields,
            title: '字体大小',
            subtitle: '调整应用字体大小',
            onTap: () => context.push('/profile/font-size-settings'),
            textScaleFactor: textScaleFactor,
          ),
          
          _buildDivider(),
          


        ],
      ),
    );
  }
  
  // 用户信息卡片
  Widget _buildUserInfoCard(BuildContext context, double textScaleFactor) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            // 用户头像
            CircleAvatar(
              radius: 40,
              backgroundColor: Theme.of(context).colorScheme.primary,
              child: const Icon(
                Icons.person,
                size: 40,
                color: Colors.white,
              ),
            ),
            const SizedBox(width: 16),
            // 用户信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'CZH',
                    style: TextStyle(
                      fontSize: 20 * textScaleFactor,
                      fontWeight: FontWeight.bold,
                      fontFamily: 'FangSong',
                      fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
                    ),
                  ),
                  const SizedBox(height: 4),
                  _isLoading
                      ? Text(
                          '加载中...',
                          style: TextStyle(
                            fontSize: 14 * textScaleFactor,
                            color: Theme.of(context).colorScheme.onSurfaceVariant,
                            fontFamily: 'FangSong',
                            fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
                          ),
                        )
                      : Text(
                          '坚持学习$_consecutiveDays天',
                          style: TextStyle(
                            fontSize: 14 * textScaleFactor,
                            color: Theme.of(context).colorScheme.onSurfaceVariant,
                            fontFamily: 'FangSong',
                            fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
                          ),
                        ),
                  const SizedBox(height: 8),
                  LinearProgressIndicator(
                    value: _consecutiveDays > 0 ? (_consecutiveDays % 100) / 100.0 : 0.0, // 基于连续天数的进度值
                    backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      Theme.of(context).colorScheme.primary,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 功能项
  Widget _buildFunctionItem({
    required BuildContext context,
    required IconData icon,
    required String title,
    String? subtitle,
    required VoidCallback onTap,
    required double textScaleFactor,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: Theme.of(context).colorScheme.primary,
      ),
      title: Text(
        title,
        style: TextStyle(
          fontSize: 16 * textScaleFactor,
          fontFamily: 'FangSong',
          fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: subtitle != null
          ? Text(
              subtitle,
              style: TextStyle(
                fontSize: 14 * textScaleFactor,
                fontFamily: 'FangSong',
                fontFamilyFallback: ['仿宋', 'FangSong', 'FangSong_GB2312'],
              ),
            )
          : null,
      trailing: const Icon(Icons.chevron_right),
      onTap: onTap,
    );
  }
  
  // 分隔线
  Widget _buildDivider() {
    return const Divider(
      height: 1,
      indent: 16,
      endIndent: 16,
    );
  }
}